package com.huawei.bitfun.insight.processor;

import com.alibaba.fastjson.JSONObject;
import com.huawei.bitfun.insight.database.ConnectionManager;
import com.huawei.bitfun.insight.database.DatabaseManager;
import com.huawei.bitfun.insight.processor.message.AddSqlStatementRequest;
import com.huawei.bitfun.insight.processor.message.DeleteRequest;
import com.huawei.bitfun.insight.type.SqlStatementTable;
import com.huawei.bitfun.insight.type.converter.SqlStatementConverter;
import com.huawei.bitfun.insight.utils.SqlStatements;
import com.huawei.deveco.insight.ohos.common.ProfilerError;
import com.huawei.deveco.insight.ohos.common.ProfilerException;
import com.huawei.deveco.insight.ohos.common.Response;
import com.huawei.deveco.insight.ohos.resourcehandler.controller.RequestMapping;
import com.huawei.deveco.insight.ohos.utils.JsonUtil;
import com.huawei.deveco.insight.ohos.utils.ValidateUtil;

import java.util.List;
import java.util.Objects;

@RequestMapping(path = "sql.statement")
public class SqlStatementProcessor {
    @RequestMapping(path = "get")
    public static Response<?> getSqlStatementList(JSONObject params) {
        try {
        List<SqlStatementTable> list = DatabaseManager.queryData(SqlStatements.GET_SQL_STATEMENT,
                ConnectionManager.getBasicDataSource(), new SqlStatementConverter()).getDataList();
        return Response.success(list);
        } catch (ProfilerException e) {
            return Response.failure(e.getInsightError());
        }
    }

    @RequestMapping(path = "add")
    public static Response<?> addSqlStatement(JSONObject params) {
        AddSqlStatementRequest request = JsonUtil.parseObject(params, AddSqlStatementRequest.class);
        ValidateUtil.validate(Objects.requireNonNull(request));
        boolean isSuccess = DatabaseManager.updateData(SqlStatements.ADD_SQL_STATEMENT,
                ConnectionManager.getBasicDataSource(), request.getName(), request.getSql());
        if (isSuccess) {
            return Response.success("success");
        }
        return Response.failure(ProfilerError.SQL_ERROR);
    }
    @RequestMapping(path = "delete")
    public static Response<?> deleteSqlStatement(JSONObject params) {
        DeleteRequest request = JsonUtil.parseObject(params, DeleteRequest.class);
        ValidateUtil.validate(Objects.requireNonNull(request));
        boolean isSuccess = DatabaseManager.updateData(SqlStatements.DELETE_SQL_STATEMENT,
                ConnectionManager.getBasicDataSource(), request.getId());
        if (isSuccess) {
            return Response.success("success");
        }
        return Response.failure(ProfilerError.SQL_ERROR);
    }
}
